﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace LikeBangumi.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class BiliInfoPage : Page
    {
        public delegate void PlayVideo(PlayModel model);
        public event PlayVideo playEvent;
        public BiliInfoPage()
        {
            this.InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Required;
        }
        WebClientClass wc;
        string banID = "";
        //bool IsBan = false;
        MyBangumi mo = new MyBangumi();
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            banID = e.Parameter as string;
            mo.Info = banID;
            mo.Type = 1;

            GetISAtt(banID);
                GetBangumiInfo(banID);

        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            wc = null;

        }
        public async void GetBangumiInfo(string banID)
        {
            //string uri = "http://bangumi.bilibili.com/api/season?_device=wp&_ulv=10000&build=411005&platform=android&appkey=422fd9d7289a1dd9&ts="+APIHelper.GetTimeSpen+ "000&type=sp&sp_id=56719";
            //string sign=  APIHelper.GetSign(uri);
            //uri += "&sign=" + sign;
            try
            {
                pr_load.Visibility = Visibility.Visible;
                wc = new WebClientClass();
                string uri = "";
                uri = string.Format("http://bangumi.bilibili.com/api/season?_device=wp&access_key={2}&_ulv=10000&build=411005&platform=android&appkey=422fd9d7289a1dd9&ts={0}000&type=bangumi&season_id={1}", BiliApiHelper.GetTimeSpen, banID, BiliApiHelper.access_key);
                uri += "&sign=" + BiliApiHelper.GetSign(uri);
                string result = await wc.GetResults(new Uri(uri));
                BangumiInfoModel model = new BangumiInfoModel();
                if ((int)JObject.Parse(result)["code"] == 0)
                {
                    model = JsonConvert.DeserializeObject<BangumiInfoModel>(JObject.Parse(result)["result"].ToString());
                    grid_Info.DataContext = model;
                    mo.Img = model.cover;
                    mo.Title = model.title;

                    BangumiInfoModel m = JsonConvert.DeserializeObject<BangumiInfoModel>(model.user_season.ToString());

                    List<BangumiInfoModel> list = JsonConvert.DeserializeObject<List<BangumiInfoModel>>(model.episodes.ToString());
                    list_E.ItemsSource = list;
                    if (list.Count != 0)
                    {
                        mo.New = list[0].index;
                    }

                    List<BangumiInfoModel> list_CV = JsonConvert.DeserializeObject<List<BangumiInfoModel>>(model.actor.ToString());
                    txt_CV.Text = "";
                    foreach (BangumiInfoModel item in list_CV)
                    {
                        txt_CV.Text += string.Format("{0}:{1}\r\n", item.role, item.actor);
                    }
                    List<BangumiInfoModel> list_Tag = JsonConvert.DeserializeObject<List<BangumiInfoModel>>(model.tags.ToString());
                    Grid_tag.Children.Clear();
                    foreach (BangumiInfoModel item in list_Tag)
                    {
                        HyperlinkButton btn = new HyperlinkButton();
                        btn.DataContext = item;
                        btn.Margin = new Thickness(0, 0, 10, 0);
                        btn.Content = item.tag_name;
                        btn.Click += Btn_Click;
                        Grid_tag.Children.Add(btn);
                    }
                }
                if ((int)JObject.Parse(result)["code"] == -3)
                {
                    messShow.Show("密钥注册失败，请联系作者", 3000);
                }
                if ((int)JObject.Parse(result)["code"] == 10)
                {
                    messShow.Show(JObject.Parse(result)["message"].ToString(), 3000);
                }
            }
            catch (Exception ex)
            {
                messShow.Show("发生错误\r\n" + ex.Message, 3000);
            }
            finally
            {
                pr_load.Visibility = Visibility.Collapsed;

            }
        }
        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            string tid = ((sender as HyperlinkButton).DataContext as BangumiInfoModel).tag_id.ToString();
            string name = ((sender as HyperlinkButton).DataContext as BangumiInfoModel).tag_name.ToString();
            if (tid != null)
            {
                this.Frame.Navigate(typeof(BiliTagInfoPage), new string[] { tid, name });
            }
        }
        private void btn_More_Click(object sender, RoutedEventArgs e)
        {
            if (txt_Desc.MaxLines == 3)
            {
                txt_Desc.MaxLines = 0;
                btn_More.Content = "收缩";
            }
            else
            {
                txt_Desc.MaxLines = 3;
                btn_More.Content = "展开";
            }
        }

        private void btn_More__Click(object sender, RoutedEventArgs e)
        {
            if (txt_CV.MaxLines == 3)
            {
                txt_CV.MaxLines = 0;
                btn_More.Content = "收缩";
            }
            else
            {
                txt_CV.MaxLines = 3;
                btn_More.Content = "展开";
            }
        }

        private void list_E_ItemClick(object sender, ItemClickEventArgs e)
        {
            BangumiInfoModel model = e.ClickedItem as BangumiInfoModel;
            playEvent(new PlayModel() { type = BangumiType.Bilibili, info = model.danmaku.ToString() });
        }

        private void btn_AddZuiFan_Click(object sender, RoutedEventArgs e)
        {
            using (var conn = AppDatabase.GetDbConnection())
            {
                // 受影响行数。
                var count = conn.Insert(mo);
                if (count==1)
                {
                    messShow.Show("已经添加到我的追番", 3000);
                    btn_AddZuiFan.IsEnabled = false;
                }
                else
                {
                    messShow.Show("添加失败", 3000);
                }
            }

        }
        private void GetISAtt(string info)
        {
            using (var conn = AppDatabase.GetDbConnection())
            {
                // 受影响行数。
                var m = from p in conn.Table<MyBangumi>()
                        where p.Info == info
                        select p;
                if (m.ToList().Count == 0)
                {
                    btn_AddZuiFan.IsEnabled = true;
                }
                else
                {
                    btn_AddZuiFan.IsEnabled = false;
                }
            }
        }

        private async void btn_OK_Click(object sender, RoutedEventArgs e)
        {
            using (DownHelper wc = new DownHelper())
            {
                if (list_E.SelectedItems.Count != 0)
                {
                    //循环读取全部选中的项目
                    foreach (BangumiInfoModel item in list_E.SelectedItems)
                    {
                        int quality = cb_Qu.SelectedIndex + 1;//清晰度1-3
                        string Downurl = await wc.GetVideoUri(item.danmaku.ToString(), quality);//取得视频URL
                        if (Downurl != null)
                        {
                            DownHelper.DownModel model = new DownHelper.DownModel()
                            {
                                mid = item.danmaku.ToString(),
                                title = "【番剧】" + txt_Name.Text,
                                part = item.index,
                                url = Downurl,
                                aid = banID,
                                quality = quality,
                                downloaded = false,
                                partTitle = item.index_title ?? "",
                                isBangumi = true
                            };
                            wc.StartDownloadBili(model);
                            //StartDownload(model);
                        }
                        else
                        {
                            MessageDialog md = new MessageDialog(item.title + "\t视频地址获取失败");
                            await md.ShowAsync();
                        }
                    }
                    messShow.Show("任务已加入下载队列", 3000);
                    list_E.SelectionMode = ListViewSelectionMode.None;
                    list_E.IsItemClickEnabled = true;
                    com_bar_Down.Visibility = Visibility.Collapsed;
                    com_bar.Visibility = Visibility.Visible;
                }
                else
                {
                    list_E.SelectionMode = ListViewSelectionMode.None;
                    list_E.IsItemClickEnabled = true;
                    com_bar_Down.Visibility = Visibility.Collapsed;
                    com_bar.Visibility = Visibility.Visible;
                }
            }

        }

        private void btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            com_bar.Visibility = Visibility.Visible;
            com_bar_Down.Visibility = Visibility.Collapsed;
            list_E.SelectionMode = ListViewSelectionMode.None;
            list_E.IsItemClickEnabled = true;
        }

        private void btn_Down_Click(object sender, RoutedEventArgs e)
        {
            com_bar.Visibility = Visibility.Collapsed;
            com_bar_Down.Visibility = Visibility.Visible;
            list_E.SelectionMode = ListViewSelectionMode.Multiple;
            list_E.IsItemClickEnabled = false;
        }
    }

    //番剧信息
    public class BangumiInfoModel
    {
        public int code { get; set; }
        public string message { get; set; }
        public object result { get; set; }

        public string alias { get; set; }//别名
        public string area { get; set; }//地区
        public string bangumi_title { get; set; }//番剧名。与season_title不同
        public string season_title { get; set; }//专题名
        public string title { get; set; }
        public string evaluate { get; set; }//介绍
        public int favorites { get; set; }//订阅
        public int coins { get; set; }//硬币
        public int play_count { get; set; }
        public int danmaku_count { get; set; }
        public int is_finish { get; set; }//是否完结
        public string newest_ep_index { get; set; }//最新话
        public string staff { get; set; }
        public string cover { get; set; }
        public DateTime? pub_time { get; set; }

        public object user_season { get; set; }
        public int attention { get; set; }//是否关注
                                          // public double last_ep_index { get; set; }//看到

        public int Num { get; set; }
        public object tags { get; set; }
        public string index { get; set; }
        public int tag_id { get; set; }
        public string tag_name { get; set; }

        public object actor { get; set; }
        public string role { get; set; }

        public object episodes { get; set; }
        public string av_id { get; set; }
        public int danmaku { get; set; }
        public string index_title { get; set; }
        public bool inLocal { get; set; }


        public int total_count { get; set; }
        public string status
        {
            get
            {
                if (is_finish == 1)
                {
                    return string.Format("已完结，共{0}话", total_count);
                }
                else
                {
                    return string.Format("连载中，更新至{0}话", newest_ep_index) ?? "";
                }
            }
        }

        public string upTime
        {
            get
            {
                if (pub_time.HasValue)
                {
                    return pub_time.Value.Date.ToString("d");
                }
                else
                {
                    return "";
                }
            }

        }

        public string PlayCount
        {
            get
            {
                if (play_count > 10000)
                {
                    return ((double)play_count / 10000).ToString("0.0" + "万");
                }
                else
                {
                    return play_count.ToString();
                }
            }
        }

        public string favoritesCount
        {
            get
            {
                if (favorites > 10000)
                {
                    return ((double)favorites / 10000).ToString("0.0" + "万");
                }
                else
                {
                    return favorites.ToString();
                }
            }
        }


    }
}
